package org.tlang.type;

import org.tlang.context.TypeTable;

public class ArrayType extends Type {
    private final Type elementType;
    private final int dimension;

    public ArrayType(Type elementType, int dimension) {
        this.elementType = elementType;
        this.dimension = dimension;
    }

    public int dimension() {
        return dimension;
    }

    public Type elementType() {
        return elementType;
    }

    @Override
    public boolean isTypeOf(Type type) {
        if (!(type instanceof ArrayType)) {
            return false;
        }
        ArrayType arrayType = (ArrayType) type;
        return arrayType.elementType == elementType && arrayType.dimension == dimension;
    }

    @Override
    public boolean isSubTypeOf(Type type, TypeTable typeTable) {
        if (!(type instanceof ArrayType)) {
            return false;
        }
        ArrayType desType = (ArrayType) type;
        return elementType.isSubTypeOf(desType.elementType, typeTable) && desType.dimension == dimension;
    }

    @Override
    public boolean isArrayType() {
        return true;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder(elementType.toString());
        for (int i = 0; i < dimension; i++) {
            stringBuilder.append("[]");
        }
        return stringBuilder.toString();
    }
}
